/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Pagination;

import java.util.List;

/**
 *
 * @author tejinder
 */
public class ListPageImpl implements Page {

    private List elements;
    private int pageSize;
    private int pageNo;

    /**
     * Construct a new ListPage. ListPage numbers are zero-based, so the first
     * page is page 0.
     *
     * @param pageNumber
     *            the page number (zero-based); if Integer.MAX_VALUE will return
     *            the last page for the query
     * @param pageSize
     *            the number of results to display on the page
     */
    public ListPageImpl(List elements, int pageNo, int pageSize) {
        this.elements = elements;
        this.pageSize = pageSize;
        this.pageNo = pageNo;

        if (Integer.MAX_VALUE == this.pageNo) {
            this.pageNo = (getTotalNumberOfElements() / this.pageSize);
        }
    }

    public boolean isFirstPage() {
        return getPageNo() == 0;
    }

    public boolean isLastPage() {
        return getPageNo() >= getLastPageNumber();
    }

    public boolean getHasNextPage() {
        return ((getPageNo() + 1) * getPageSize()) < (getTotalNumberOfElements() + 1);
    }

    public boolean getHasPreviousPage() {
        return getPageNo() > 0;
    }

    public int getLastPageNumber() {
        double totalResults = Integer.valueOf(getTotalNumberOfElements()).doubleValue();

        return new Double(Math.floor(totalResults / getPageSize())).intValue();
    }

    public List getThisPageElements() {
        final int start = getPageNo() * getPageSize();

        return elements.subList(Math.min(start, getTotalNumberOfElements() + 1),
            Math.min(start + getPageSize(), getTotalNumberOfElements() + 1));
    }

    /**
     * this is 0-based, differently from list.size();
     */
    public int getTotalNumberOfElements() {
        return elements.size() - 1;
    }

    public int getThisPageFirstElementNumber() {
        return (getPageNo() * getPageSize()) + 1;
    }

    public int getThisPageLastElementNumber() {
        int fullPage = (getThisPageFirstElementNumber() + getPageSize()) - 1;

        return (getTotalNumberOfElements() < fullPage) ? getTotalNumberOfElements() : fullPage;
    }

    public int getNextPageNumber() {
        return getPageNo() + 1;
    }

    public int getPreviousPageNumber() {
        return getPageNo() - 1;
    }

    public int getPageSize() {
        return pageSize;
    }

    public int getPageNo() {
        return pageNo;
    }

}
